package net.hound.site.video;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.cl.support.json.JsonArray;
import net.cl.support.json.JsonObject;
import net.cl.tools.Validator;
import net.cl.utils.HttpUtil;
import net.cl.utils.StringUtil;
import net.hound.IHound;

/**
 * @author caol64@gmail.com
 * 
 */
public class Letv implements IHound {

	private static final String INDEX_PREFIX2 = "http://app.letv.com/v.php?id=";
	private String url;
	private static final String encoding = "UTF-8";

	public Letv(String url) {
		this.url = url;
	}

	public String getSource(String userAgent) {
		String vid = StringUtil.getMatch("^http://www.letv.com/ptv/vplay/(\\d{1,}).html$", url);
		if (vid == null)
			return "media not found.";
		String indexUrl = INDEX_PREFIX2 + vid;
		try {
			String html = HttpUtil.getResponseString(indexUrl, encoding);
			Document doc = Jsoup.parse(html);
			JsonObject jsonObj = null;
			Elements es = doc.select("error_msg");
			if (es != null && es.size() > 0 && Validator.isNotEmpty(es.first().text())) {
				return es.first().text();
			} else {
				Element e = doc.select("mmsJson").first();
				jsonObj = JsonObject.fromString(e.text().replace("\\", ""));
			}
			StringBuilder sb = new StringBuilder();
			JsonArray jsonArray = jsonObj.getJsonObject("bean").getJsonArray("video");
			for (int i = 0; i < jsonArray.size(); i++) {
				try {
					jsonObj = jsonArray.getJsonObject(i);
					jsonObj = JsonObject.fromString(HttpUtil.getResponseString(jsonObj.getString("url"), encoding));
					if (sb.length() > 0)
						sb.append("[=]");
					sb.append(HttpUtil.finalRedirect(jsonObj.getString("location")));
				} catch (Exception e1) {
				}
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getInfo(String userAgent) {
		// TODO Auto-generated method stub
		return null;
	}

}
